import { segment } from 'oicq'
import plugin from '../../../lib/plugins/plugin.js'
import Config from '../models/Config.js'
import fetch from 'node-fetch'

export class xy_ai extends plugin {
    constructor() {
        super({
            name: '小月ai',
            dsc: 'ai',
            event: 'message',
            priority: -Infinity,
            rule: [{
                reg: "",
                fnc: "ai",
                log: false
            }]
        })
    }

    async ai(e) {
        if (!Config.getConfig().ai) return false
        const { custom } = Config.getConfig()
        Object.entries(custom).forEach(async ([key, value]) => {
            if (e.msg === key) {
                const roll = Math.random()
                if (roll < Config.getConfig().random) {
                    if (value.image?.length > 0) {
                        e.reply(segment.image(value.image[Math.floor(Math.random() * value.image.length)]))
                        return true
                    }
                } else if (roll < Config.getConfig().random + Config.getConfig().random_video) {
                    if (value.video?.length > 0) {
                        const video = value.video[Math.floor(Math.random() * value.video.length)]
                        const res = await fetch(video)
                        if (res.status === 302) {
                            const locationUrl = res.headers.get('Location')
                            if (locationUrl) {
                                res = await fetch(locationUrl)
                            } else {
                                logger.error("Location header not found in response.")
                                return false
                            }
                        }
                        if (!res.ok) {
                            logger.error(`Failed to fetch video: ${res.status}`)
                            return false
                        }
                        const arrayBuffer = await res.arrayBuffer()

                        e.reply(segment.video(Buffer.from(arrayBuffer)))
                        return true
                    }
                } else if (roll < Config.getConfig().random + Config.getConfig().random_video + Config.getConfig().random_record) {
                    if (value.record?.length > 0) {
                        e.reply(segment.record(value.record[Math.floor(Math.random() * value.record.length)]))
                        return true
                    }
                } else {
                    if (value.text?.length > 0) {
                        e.reply(value.text[Math.floor(Math.random() * value.text.length)])
                        return true
                    }
                }
            }
        })
        return false
    }
}